package com.ks.api.controller;

import com.ks.api.entity.KsConfigSc;
import com.ks.api.mapper.KsConfigScMapper;
import com.ks.api.service.KuaishouTokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 快手API控制器
 */
@Slf4j
@RestController
@RequestMapping("/kuaishou")
@RequiredArgsConstructor
public class KuaishouController {

    private final KuaishouTokenService kuaishouTokenService;
    private final KsConfigScMapper KsConfigScMapper;
    
    @Value("${kuaishou.miniapp.default_app_id}")
    private String defaultAppId;

    /**
     * 获取当前token状态（仅用于测试）
     */
    @GetMapping("/token/status")
    public Map<String, Object> getTokenStatus(@RequestParam(required = false) String appId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (appId == null) {
                appId = defaultAppId;
            }
            
            String accessToken = kuaishouTokenService.getAccessToken(appId);
            result.put("success", true);
            result.put("appId", appId);
            result.put("accessToken", accessToken.substring(0, 10) + "...");
        } catch (Exception e) {
            log.error("获取token状态失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取所有应用的token状态
     */
    @GetMapping("/token/status/all")
    public Map<String, Object> getAllTokenStatus() {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> tokensMap = new HashMap<>();
        
        try {
            List<KsConfigSc> KsConfigScs = KsConfigScMapper.getAllKsConfigScs();
            
            for (KsConfigSc config : KsConfigScs) {
                String appId = config.getAppDh();
                try {
                    String accessToken = kuaishouTokenService.getAccessToken(appId);
                    Map<String, String> tokenInfo = new HashMap<>();
                    tokenInfo.put("accessToken", accessToken.substring(0, 10) + "...");
                    tokenInfo.put("appName", config.getAppName());
                    tokensMap.put(appId, tokenInfo);
                } catch (Exception e) {
                    Map<String, String> errorMap = new HashMap<>();
                    errorMap.put("error", e.getMessage());
                    tokensMap.put(appId, errorMap);
                }
            }
            
            result.put("success", true);
            result.put("tokens", tokensMap);
        } catch (Exception e) {
            log.error("获取所有token状态失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 手动刷新token（仅用于测试）
     */
    @GetMapping("/token/refresh")
    public Map<String, Object> refreshToken(@RequestParam(required = false) String appId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (appId == null) {
                appId = defaultAppId;
            }
            
            kuaishouTokenService.refreshToken(appId);
            result.put("success", true);
            result.put("appId", appId);
            result.put("message", "Token刷新成功");
        } catch (Exception e) {
            log.error("刷新token失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 刷新所有应用的token
     */
    @GetMapping("/token/refresh/all")
    public Map<String, Object> refreshAllTokens() {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> refreshResults = new HashMap<>();
        
        try {
            List<KsConfigSc> KsConfigScs = KsConfigScMapper.getAllKsConfigScs();
            
            for (KsConfigSc config : KsConfigScs) {
                String appId = config.getAppDh();
                try {
                    kuaishouTokenService.refreshToken(appId);
                    Map<String, Object> successMap = new HashMap<>();
                    successMap.put("success", true);
                    successMap.put("appName", config.getAppName());
                    refreshResults.put(appId, successMap);
                } catch (Exception e) {
                    Map<String, Object> errorMap = new HashMap<>();
                    errorMap.put("success", false);
                    errorMap.put("error", e.getMessage());
                    refreshResults.put(appId, errorMap);
                }
            }
            
            result.put("success", true);
            result.put("results", refreshResults);
        } catch (Exception e) {
            log.error("刷新所有token失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
} 